package com.bjpower.job;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.bjpower.entity.TradeOrder;
import com.bjpower.job.headler.TradOrderEachDayBillHeader;
import com.bjpower.mapper.TradeOrderMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Date;
import java.util.List;

@Component
public class JobManager {

    @Resource
    private TradeOrderMapper tradeOrderMapper;

    @Value("${bill.path}")
    private String billPath = "";

    @XxlJob("createJob")
    public void createJob(){
        //当前时间
        Date nowTime = new Date();
        //开始时间是当前时间减去一天的时间然后进行截取
        Date timeStart = DateUtil.offsetDay(nowTime, -1);
        //再文件下每天创建一个日期目录来保存不同商家账单信息
        String directName = DateTimeFormatter.ofPattern("yyyyMMdd").format((TemporalAccessor) timeStart);
        try {
            Path path = Paths.get(billPath, directName);
            if (!Files.exists(path)){
                Files.createDirectories(path);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        Date startTime = DateUtil.truncate(timeStart, DateField.DAY_OF_MONTH);
        //结束时间
        Date endTime = DateUtil.truncate(nowTime, DateField.DAY_OF_MONTH);
        List<String> userNoList = tradeOrderMapper.selectUserNoList(startTime, endTime);
        String fileName = "";
        for (String userNo : userNoList){
            //根据商户号查询出账单信息
            List<TradeOrder> billList = tradeOrderMapper.selectBillList(userNo, startTime, endTime);
            fileName = billPath + directName + "/" + userNo + "bill.xlsx";
            EasyExcel.write(fileName, TradOrderEachDayBillHeader.class)
                    .sheet("商家对账表")
                    .doWrite(billList);
        }
    }
}
